﻿using DotNetCommon.Extensions;
using System;
using System.Text;
using System.Text.RegularExpressions;

namespace DotNetCommon;

/// <summary>
/// unicode 编解码
/// <list type="bullet">
/// <item>解码: "空\u0020格" => "空 格"</item>
/// <item>编码: "空 格" => "\u7a7a\u0020\u683c"</item>
/// </list>
/// </summary>
public static class UnicodeHelper
{
    /// <summary>
    /// Unicode编码, "空 格" => "\u7a7a\u0020\u683c"
    /// </summary>
    public static string EnUnicode(string str)
    {
        if (str.IsNullOrEmpty()) return str;
        var strResult = new StringBuilder();
        for (int i = 0; i < str.Length; i++) strResult.Append(string.Format("\\u{0:x4}", (int)str[i]));
        return strResult.ToString();
    }

    /// <summary>
    /// Unicode解码, "空\u0020格" => "空 格"
    /// </summary>
    public static string DeUnicode(string str)
    {
        if (str.IsNullOrWhiteSpace()) return str;
        //最直接的方法 Regex.Unescape(str);
        var reg = new Regex(@"(?i)\\[uU%]([0-9a-f]{4})");
        return reg.Replace(str, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
    }
}
